<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="40px"
    >
      <el-form-item label="楼宇" prop="buildingId">
        <el-select v-model="queryParams.buildingId" placeholder="请选择楼宇">
          <el-option v-for="i in buildList" :key="i.id" :label="i.name" :value="i.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-select v-model="queryParams.floor" placeholder="请选择楼层" clearable>
          <el-option
            v-for="i in floorList"
            :key="i.floor"
            :label="i.floor"
            :value="i.floor"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="deviceName">
        <el-select
          v-model="queryParams.deviceName"
          filterable
          clearable
          placeholder="请选择AI识别设备名称"
        >
          <el-option
            v-for="(i, index) in deviceList"
            :key="index"
            :label="i.aiName"
            :value="i.aiName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="可信度<=" prop="confidence" label-width="80px">
        <el-input
          v-model="queryParams.confidence"
          placeholder="请输入可信度"
          maxlength="3"
          clearable
          @input="handleConfidence"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-tabs value="全部">
      <el-tab-pane :label="`全部(${total})`" name="全部" />
    </el-tabs>
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="楼宇" align="center" prop="buildingName" sortable />
      <el-table-column label="楼层" align="center" sortable>
        <template slot-scope="scope">
          {{ scope.row.buildingFloor ? scope.row.buildingFloor.floor : "" }}
        </template>
      </el-table-column>
      <el-table-column label="AI识别名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.systemDevice ? scope.row.systemDevice.aiName : "" }}
        </template>
      </el-table-column>
      <el-table-column label="标准设备名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.systemDevice ? scope.row.systemDevice.name : "" }}
        </template>
      </el-table-column>
      <el-table-column label="可信度" align="center">
        <template slot-scope="scope">
          <!-- color: scope.row.predictPointxyVOList[0].confidence < trustNum ? '#F56C6C' : '#606266', -->
          <span
            :style="{
              color: '#606266',
            }"
          >
            {{ Math.floor((scope.row.predictPointxyVOList[0].confidence || 0) * 100) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="图纸缩略图" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)"> 查看 </el-button>
        </template>
      </el-table-column>
      <el-table-column label="缩略图" align="center">
        <template slot-scope="scope">
          <canvas :id="'thumbnail_' + scope.row.virtualId" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.systemDevice && !scope.row.systemDevice.name"
            type="text"
            icon="el-icon-edit"
            @click="updateDevice(scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="removeDevice(scope.row.virtualId)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div style="display: flex; justify-content: center; margin-top: 1rem">
      <el-button
        size="medium"
        plain
        icon="el-icon-back"
        style="margin-right: 1rem"
        @click="handleLast"
      >
        上一步
      </el-button>
      <el-button size="medium" icon="el-icon-right" type="primary" @click="handleNext">
        暂存并下一步
      </el-button>
    </div>
    <el-dialog title="修改" :visible.sync="updateShow" width="500px">
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="120px">
        <el-form-item label="标准设备名称" prop="deviceId">
          <el-select
            v-model="editForm.deviceId"
            filterable
            placeholder="请输入标准设备名称"
            style="width: 100%"
          >
            <el-option
              v-for="(i, index) in deviceAllList"
              :key="index"
              :label="i.aiName"
              :value="i.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="updateShow = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate" :loading="editLoading">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <View-image
      v-if="filepath"
      :src="filepath"
      :start="startxy"
      :end="endxy"
      @close="handleClose"
    />
    <!-- <el-image-viewer
      v-if="filepath"
      :on-close="() => (filepath = '')"
      :url-list="[filepath]"
    /> -->
  </div>
</template>

<script>
import ViewImage from "./cp/ViewImage.vue";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { getBuildList } from "@/api/contract/contractOrg";
import {
  postAiPredict,
  getAliasList,
  deleteAiPredict,
  settingGetInfo,
  getAiNameList,
  updatePredict,
} from "@/api/system/ai";
import { getBuildingFloorList } from "@/api/system/building";
export default {
  name: "TwoLead",
  components: { ElImageViewer, ViewImage },
  data() {
    return {
      loading: false, // 遮罩层
      queryParams: {
        // 查询参数
        pageNum: 1,
        pageSize: 10,
        buildingId: null, // 建筑id
        floor: null, // 楼层id
        deviceName: null, // 设备名称
        cache: true, // 查缓存（固定的）
        confidence: null,
      },
      info: {}, // 表单信息
      dataList: [], // 数据列表
      total: 0, // 总条数
      // trustNum: 0, // 信任度
      buildList: [], // 建筑列表
      floorList: [], // 楼层列表
      deviceList: [], // 设备列表
      deviceAllList: [], // 设备列表
      filepath: "", // 临时文件路径
      startxy: [0, 0], // 鼠标开始位置
      endxy: [0, 0], // 鼠标结束位置
      updateShow: false, // 修改弹窗
      editForm: {
        aiName: null, // 设备名称
        buildingId: null, // 建筑id
        deviceId: null, // 设备id
      }, // 修改表单
      editLoading: false, // 提交中
      rules: {
        deviceId: [{ required: true, message: "请输入标准设备名称", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 初始化数据
    init(info, data, total = 0) {
      this.info = info;
      this.total = total;
      this.queryParams.buildingId = this.info.buildingId;
      this.getList();
      this.getBuilds();
      this.getFloors();
      this.getDeviceList();
      // this.geTrustLevel();
    },
    // 获取建筑列表
    getBuilds() {
      getBuildList({ customerId: this.info.customerId }).then((res) => {
        this.buildList = res.rows.filter((i) => i.id == this.info.buildingId);
      });
    },
    // 获取楼层列表
    getFloors() {
      getBuildingFloorList(this.queryParams.buildingId).then((res) => {
        this.floorList = res.data;
      });
    },
    handleConfidence(e) {
      if (isNaN(e) || !e) {
        this.queryParams.confidence = null;
      } else if (/^(100|([1-9]?[0-9]|0))$/.test(e)) {
        this.queryParams.confidence = e;
      } else {
        this.queryParams.confidence = null;
      }
    },
    // 获取设备列表
    getDeviceList() {
      getAiNameList(this.queryParams.buildingId).then((res) => {
        this.deviceList = res.data;
      });
    },
    // 获取信任度
    // geTrustLevel() {
    //   settingGetInfo("AI_TRUST_LEVEL").then((res) => {
    //     this.trustNum = parseFloat(res.data.value || "100") / 100;
    //   });
    // },
    /** 查询AI识别设备列表 */
    getList() {
      this.loading = true;
      postAiPredict(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          setTimeout(() => {
            this.dataList.forEach((i) => {
              this.parseCoordinate(i);
            });
          }, 0);
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.buildingId = this.info.buildingId;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 查看图纸
    handleView(row) {
      this.filepath = row.buildingThumbnail;
      if (row.predictPointxyVOList) {
        this.startxy = row.predictPointxyVOList[0]?.xy;
        this.endxy = row.predictPointxyVOList[0]?.xy2;
      }
    },
    // 关闭预览
    handleClose() {
      this.filepath = "";
      this.startxy = [0, 0];
      this.endxy = [0, 0];
    },
    // 解析坐标
    parseCoordinate(row) {
      const { virtualId, buildingThumbnail, predictPointxyVOList } = row;
      const [x, y] = predictPointxyVOList[0]?.xy || [0, 0];
      const [x1, y1] = predictPointxyVOList[0]?.xy2 || [0, 0];
      let w = x1 - x;
      let h = y1 - y;
      let canvas = document.getElementById("thumbnail_" + virtualId);
      const ctx = canvas.getContext("2d");
      const img = new Image();
      let ow, oh;
      img.src = buildingThumbnail;
      img.onload = () => {
        ow = img.width;
        oh = img.height;
        console.log(ow, oh);
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(img, x, y, ow, oh, 0, 0, ow, oh);
      };
    },
    // 编辑按钮操作
    updateDevice(row) {
      this.editForm.aiName = row.systemDevice.aiName;
      this.editForm.buildingId = row.buildingId;
      this.editForm.deviceId = "";
      getAliasList().then((res) => {
        this.deviceAllList = res.data;
        this.updateShow = true;
      });
    },
    // 提交修改
    handleUpdate() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.editLoading = true;
          updatePredict(this.editForm)
            .then((res) => {
              this.$message.success("修改成功");
              this.getList();
              this.updateShow = false;
            })
            .finally(() => {
              this.editLoading = false;
            });
        }
      });
    },
    // 移除AI识别设备
    removeDevice(id) {
      this.$confirm("是否确认移除该设备?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteAiPredict({
            buildingId: this.queryParams.buildingId,
            ids: [id],
          });
          this.$message.success("移除成功");
          this.getList();
        })
        .catch(() => {});
    },
    // 上一步
    handleLast() {
      this.queryParams.pageNum = 1;
      this.queryForm.floor = null;
      this.queryForm.deviceName = null;
      this.queryForm.confidence = null;
      this.$cache.local.remove("ai-predict");
      this.$emit("refresh", { step: 1 });
    },
    // 下一步
    handleNext() {
      this.$cache.local.setJSON("ai-predict", {
        step: 3,
        form: this.info,
        success: false,
      });
      this.$emit("refresh", { step: 3, form: this.info, success: false });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-image-viewer__wrapper {
  z-index: 3000 !important;
}
</style>
